/**
 * 定时任务管理器
 * @author yanwl 
 * @date 2014-11-20
 */
package com.chnbst.bstyun.task;

import java.text.ParseException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import com.chnbst.bstyun.core.common.DateUtil;
import com.chnbst.bstyun.core.common.ReadProperties;
import com.chnbst.bstyun.core.common.SignUtil;
import com.chnbst.bstyun.model.pojo.Order;
import com.chnbst.bstyun.model.pojo.Payment;
import com.chnbst.bstyun.model.pojo.User;
import com.chnbst.bstyun.model.vo.OrderVo;
import com.chnbst.bstyun.service.MealProductService;
import com.chnbst.bstyun.service.MealService;
import com.chnbst.bstyun.service.OrderService;
import com.chnbst.bstyun.service.PaymentService;
import com.chnbst.bstyun.service.ProductService;
import com.chnbst.bstyun.service.UserService;
import com.chnbst.mail.EmailUtil;

@Component
public class Task {
	@Autowired
	private OrderService orderService;
	@Autowired
	private UserService userService;
	@Autowired
	private MealProductService mealProductService;
	@Autowired
	private ProductService productService;
	@Autowired
	private ReadProperties read;
	@Autowired
	private MealService mealService;
	@Autowired
	private PaymentService paymentService;
	
	/*续费提醒*/
	@Scheduled(cron = "0 0 0 * * ?") 
	public void sendRenewRemind() throws ParseException { 
		//7天后的日期
		Date overTime = SignUtil.getOvertime(5, +7, new Date());
		
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("userId", null);
		map.put("overTime", overTime);
		map.put("sortField", "pay_time");
		map.put("sortOrder", "desc");
		map.put("groupField", "t.user_id,t.meal_id,t.new_pro_id");
		List<OrderVo> orders = orderService.selectLastOrdersByUserId(map);
		
		for (OrderVo order : orders) {
			String proMealName = order.getMealName();
			Date proOverTime = order.getProOverTime();
			String overTimeStr = SignUtil.time2str(proOverTime, "yyyy-MM-dd hh:mm");
			String dayStr = DateUtil.getMonth("getOverTime", new Date(), proOverTime);
			String dateStr = dayStr+"后（"+overTimeStr+"）";
			Integer orderId = order.getOrderId();
			String url = read.getBstyunUrl()+"/myservice/order/toRenewPage?orderId="+orderId;
			String a = "<a href='"+url+"'>续费</a>";
			Integer userId = order.getUserId();
			User user = userService.selectUserInfoByUserId(userId);
			EmailUtil.sendMailRenew(user.getPersonEmail(), new String[]{user.getUserEmail(),proMealName,dateStr,a});
			
			Integer parentId = order.getParentId();
			if(parentId != userId){
				User registerUser = userService.selectUserInfoByUserId(parentId);
				String userInfoName = registerUser.getUserEmail();
				if(SignUtil.isNotEmpty(registerUser.getUserEmail())) {
					EmailUtil.sendMailRenew(userInfoName, new String[]{userInfoName,proMealName,dateStr,a});
				}
			}
		}
	} 
	
	/*未付款的订单取消*/
//	@Scheduled(fixedRate = 10000) 
	@Scheduled(fixedRate = 3600000) 
    public void closeNoPayOrder() { 
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("orderState", 1);
		map.put("userId", null);
		List<Order> orders = orderService.selectOrdersByMap(map);
		for (Order order : orders) {
			long closeTime = SignUtil.getOvertime(5, +7, order.getOccurTime()).getTime();
			long currTime = new Date().getTime();
			if(closeTime < currTime) {
				if(order.getNewProId() == null) {
					map.put("orderState", 0);
					map.put("userId", order.getUserId());
					List<Order> list = orderService.selectOrdersByMap(map);
					if(list.size() <= 0) {
						User user = userService.selectUserInfoByUserId(order.getUserId());
						if(user != null) {
							user.setUserValid("1");
							user.setIsLive("0");
							userService.updateUserByKey(user);
						}
					}
				}
				Payment payment = paymentService.selectPaymentByOrderId(order.getOrderId());
				if(payment != null) {
					payment.setIsCancel(1);
					paymentService.updatePayment(payment);
				}
				order.setOrderState("2");
				orderService.updateOrderByOrderId(order);
			}
		}
    } 
	
	/*到期后的订单在一定时间内订单取消*/
	@Scheduled(cron = "0 0 0 * * ?") 
	public void closeTimeOutOrder() { 
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("orderState", 0);
		map.put("userId", null);
		map.put("isMeal", 1);
		map.put("useLife", "0");
		List<Order> orders = orderService.selectOrdersByMap(map);
		for (Order order : orders) {
			long closeTime = SignUtil.getOvertime(5, +20, order.getOverTime()).getTime();
			long currTime = new Date().getTime();
			if(closeTime < currTime) {
				User user = userService.selectUserInfoByUserId(order.getUserId());
				if(user != null) {
					user.setUserValid("1");
					user.setIsLive("0");
					userService.updateUserByKey(user);
				}
				order.setOrderState("2");
				orderService.updateOrderByOrderId(order);
			}
		}
	} 
}
